<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
 
class User extends MY_Controller {
 
    public function __construct() {
        parent::__construct();
        $this->load->library('form_validation');
        //设置表单错误分隔符，设置为空，直接输出即可
        $this->form_validation->set_error_delimiters('','');
        $this->load->model('member_model', 'member');
        $this->load->helper('public');
        $this->load->helper("cookie");
        ini_set("display_errors", "On"); 
        error_reporting(E_ALL | E_STRICT);
    }
 
    //检测是否已经登录
    protected function isLogined(){
        $id = isset($_SESSION["passid"]) ? $_SESSION["passid"] : "";
 
        if (!empty($id)){
            $this->roleLogin($id);
            return;
        }
 
        $rd_cookie = $this->input->cookie("rd_passport");
        if (!empty($rd_cookie)) {
            $decode = authcode($rd_cookie, "DECODE", $this->config->item("password_encode_key"));
            $arr = explode("_", $decode);
            $member["id"] = intval($arr[0]);
            $member["idnumber"] = intval($arr[1]);
            $memberData = $this->member->select_one_by_field('id', $member["id"]);
            if ($memberData["idnumber"] == $member["idnumber"]) {
                $this->passLogin($memberData, 1);
                $this->roleLogin($member["id"]);
            }
        }
 
    }
 
    public function logout(){
        unset($_SESSION["passid"]);
        unset($_SESSION["stuID"]);
        delete_cookie("rd_passport");
 
        if (isset($_SERVER['HTTP_REFERER'])){
            $url = $_SERVER['HTTP_REFERER'];
            $pattern = array(
                "/^".format_preg_string($this->config->item("bbs_path")).".*$/i");
                /*"/^".format_preg_string($this->config->item("base_url")).".*$/i");*/ //家园账户中注销，不需要回到那个页面
            foreach ($pattern as $key => $value) {
                if (!preg_match($value, $url)) {
                    $match[] = 0;
                } else {
                    $match[] = 1;
                }
            }
            $r = 0;
            foreach ($match as $key => $value) {
                $r += $value;
            }
            if ($r == 0) {
                log_message("error", "来源地址不正确");
                show_message("注销成功".uc_user_synlogout(), site_url("/user/login"));
            } else {
                show_message("注销成功".uc_user_synlogout(), $url);
            }
        } else {
            log_message("error", "来源地址为空");
            show_message("注销成功".uc_user_synlogout(), site_url("/user/login"));
        }
 
 
    }
 
    public function index() {
        redirect("/user/login");
    }
 
    public function login() {
        $this->isLogined();
        $config = array(
            array(
                'field' => 'account',
                'label' => '邮箱',
                'rules' => 'trim|required|callback_check_account'
                ),
            array(
                'field' => 'password',
                'label' => '密码',
                'rules' => 'trim|required'
                )
        );
        $this->form_validation->set_rules($config);
        $this->form_validation->set_message('required', '<i class="icon-exclamation-sign"></i>此项必填');
        $this->form_validation->set_message('check_email', '<i class="icon-exclamation-sign"></i>请使用学号或者邮箱登陆');
 
        if ($this->form_validation->run() == FALSE) {
            $this->load->view('/user/login');
        } else {
            $account = $this->input->post('account');
            $password = $this->input->post('password');
 
            if (empty($account)) {
                $data['error'] = '用户名或者密码错误';
                $this->load->view('/user/login', $data);
                return;
            }
 
            if (empty($password)) {
                $data['error'] = '用户名或者密码错误';
                $this->load->view('/user/login', $data);
                return;
            }
            $idnumberPattern = "/^[0-9]{8,9}$/u";
 
            if (preg_match($idnumberPattern, $account)) {
                $member = $this->member->select_one_by_field('idnumber', $account);
            } else {
                $member = $this->member->select_one_by_field('email', $account);
            }
 
 
            if (empty($member)) {
                $data['error'] = '邮箱或者学号尚未注册';
                $this->load->view('/user/login', $data);
                return;
            }
            //预留一个status，可以使得管理员禁止某些member登录
            if ($member['status'] === 0) {
                $data['error'] = '您的用户已经被管理员锁定';
                $this->load->view('/user/login', $data);
                return;
            }            
            //查看来访ip是否在被禁止ip的有效时间之内
            $ip = get_client_ip();
 
            if ($this->member->check_ip_banned($member["id"], $ip)) {
                $data['error'] = '密码错误次数太多，IP已经被禁止，请更换ip或者10分钟后再试';
                $this->load->view('/user/login', $data);
                return;
            }
 
            if ($member["password"] != rd_encode_password($password, $member["salt"])){
                $this->member->insert_log($member["id"], $ip, 0);
                $times = $this->member->get_last_login_fails($member["id"], $ip);
                if (intval($times['failedTimes']) >= $this->config->item("maxFailedTimes")) {
                    $this->member->insert_ipbanned($member["id"], $ip);
                    $data['error'] = '您的账户因为尝试次数过多，已经被锁定';
                } else {
                    $times = intval($this->config->item("maxFailedTimes")) - intval($times['failedTimes']);
                    $data['error'] = '密码错误，还剩余'.$times.'次';
                }
                $this->load->view('/user/login', $data);
                return;
            }
 
            // $isRember = $this->input->post("checkbox-remeber");
            // if (!empty($isRember) && $isRember == "1"){
            //     $this->passLogin($member, 1);
            // } else {
            //     $this->passLogin($member, 0);
            // }
            $this->passLogin($member, 0);
            //检测教务密码和数据库中保存的密码是否已经发生变化
            /*if (authcode($member["password"], "DECODE", $this->config->item("password_encode_key")) != $password) {
                if (!$this->member->update_password($member["id"], $password)) {
                    log_message("error", "修改已经绑定的密码失败");
                    show_error("修改已经绑定的密码失败，请联系管理员");
                }
            }*/
            //检测图书馆密码是否发生改变
            //$libAccount = $this->member->get_lib_password($member["idnumber"]);
            //如果没有图书馆密码绑定的话，就不要检测了
            // if (!empty($libAccount)) {
            //     if (!checkLibPassword($member["idnumber"], authcode($libAccount["password"], "DECODE", $this->config->item("password_encode_key")))) {
            //         log_message('error', $member["idnumber"]."的图书馆密码是".$libAccount["password"]);
            //         show_message("检测到您的图书馆账号密码已经改动，请重新绑定", site_url("home/lib"));
            //         return;
            //     }
            // }
 
            $this->roleLogin($member['id']);            
        }
    }
 
    public function register() {
        $this->isLogined();
        $config = array( //字段验证规则
            array(
                "field" => "red_email",
                "label" => "邮箱",
                "rules" => "trim|required|callback_check_email|min_length[4]|max_length[50]"
                ),
            array(
                "field" => "red_password",
                "label" => "密码",
                "rules" => "trim|required|min_length[6]|max_length[20]"
                ),
            array(
                "field" => "red_repassword",
                "label" => "重复密码",
                "rules" => "trim|required|matches[red_password]"
                ),
            array(
                "field" => "stuID",
                "label" => "学（工）号",
                "rules" => "trimtrim|required|callback_check_stuID"
                ),
            array(
                "field" => "realname",
                "label" => "姓名",
                "rules" => "trim|required|min_length[2]|max_length[20]"
                ),
            array(
                "field" => "year",
                "label" => "出生年",
                "rules" => "trim|required"
                ),
            array(
                "field" => "month",
                "label" => "出生月",
                "rules" => "trim|required"
                ),
            array(
                "field" => "day",
                "label" => "出生日",
                "rules" => "trim|required"
                )
            /*验证码字段
            array(
                "field" => "",
                "label" => "",
                "rules" => ""
                ),*/
            );
        $this->form_validation->set_rules($config);
        $this->form_validation->set_message('required', '<i class="icon-exclamation-sign"></i>此项必填');
        $this->form_validation->set_message('check_email', '<i class="icon-exclamation-sign"></i>用户名格式不正确');
        $this->form_validation->set_message('check_stuID', '<i class="icon-exclamation-sign"></i>学号格式不正确');
        $this->form_validation->set_message('matches', '<i class="icon-exclamation-sign"></i>两个密码不一致');
        $this->form_validation->set_message('min_length', '<i class="icon-exclamation-sign"></i>%s长度至少为%s位');
        $this->form_validation->set_message('max_length', '<i class="icon-exclamation-sign"></i>%s长度至多为%s位');
 
        if ($this->form_validation->run() == FALSE) {
            $this->load->view('/user/register');
        } else {
            header("Content-type:text/html;charset=utf-8");
            $email    = strtolower($this->input->post("red_email"));
            $password = $this->input->post("red_password");
            $stuID    = $this->input->post("stuID");
            $stuname  = $this->input->post("realname");
            $year     = $this->input->post("year");
            $month    = $this->input->post("month");
            $day      = $this->input->post("day");
            //通过实名接口获取实名信息 函数定义在/helpers/public_helper.php内
            $autonym = getinterfaceflag($stuID);
 
            if ($autonym["interfaceflag"] == -2) {
                $data["error"] = "无法连接实名验证服务器";
                $this->load->view("/user/register", $data);
                return ;
            }
 
            //学号不存在
            if ($autonym["interfaceflag"] == -1) {
                $autonyminfo = $this->member->get_autonym($stuID);
                if (!$autonyminfo) {
                    $data["error"] = "该学号不存在";
                    $this->load->view("/user/register", $data);
                    return;
                }
                if ($autonyminfo["realname"] != $stuname) {
                    $data["error"] = "真实姓名与学号不匹配";
                    $this->load->view("/user/register", $data);
                    return;
                }
 
                if ($autonyminfo["birth"] != strtotime($year.'_'.$month.'_'.$day)) {
                    $data["error"] = "生日与学号信息不匹配";
                    $this->load->view("/user/register", $data);
                    return;
                }
 
            } else{
                if ($autonym["user_name"] != $stuname) {
                    $data["error"] = "真实姓名与学号不匹配";
                    $this->load->view("/user/register", $data);
                    return;
                }
 
                if ($autonym["user_birth"] != $year.'-'.$month.'-'.$day) {
                    $data["error"] = "生日与学号信息不匹配";
                    $this->load->view("/user/register", $data);
                    return;
                }
            }
 
            $stu = $this->member->select_one_by_field("idnumber", $stuID);
 
            if (!empty($stu)){
                $data['error'] = "该学号已经被注册";
                $this->load->view('/user/register', $data);
                return ;
            }
            $salt = getRandomString(5);//产生一个5个字符长度的随机字符串，用于给密码加密提供一个key
            $result = array(
                "idnumber" => $stuID,
                "email" => $email,
                "password" => rd_encode_password($password, $salt),
                "salt" => $salt,
                "regdate" => time()
                );
 
            $passid = $this->member->insert_member($result);
 
              if (empty($passid)) {
                log_message("error", "注册信息插入失败，没有返回passid");
                $data['error'] = "信息插入失败，请联系管理员";
                $this->load->view('/user/register', $data);
                return ;
            }
            $member["id"] = $passid;
            $member["idnumber"] = $stuID;
 
            $this->passLogin($member);
            unset($member);
            $_SESSION["needMail"] = 1;
            redirect("/home/mail");    //跳转到接受邮箱的页面       
        }
    }
    //找回密码
    public function forgetpassword() {
        $config = array(
            array(
                "field" => "red_email",
                "label" => "邮箱",
                "rules" => "trim|required|callback_check_email|min_length[4]|max_length[50]"
                ),
            array(
                "field" => "red_captcha",
                "label" => "验证码",
                "rules" => "trim|required|callback_check_captcha|min_length[4]|max_length[4]|"
                )
            );
        $this->form_validation->set_rules($config);
        $this->form_validation->set_message('required', '<i class="icon-exclamation-sign"></i>此项必填');
        $this->form_validation->set_message('check_email', '<i class="icon-exclamation-sign"></i>用户名格式不正确');
        $this->form_validation->set_message('min_length', '<i class="icon-exclamation-sign"></i>%s长度至少为%s位');
        $this->form_validation->set_message('max_length', '<i class="icon-exclamation-sign"></i>%s长度至多为%s位');
        $this->form_validation->set_message('check_captcha', '<i class="icon-exclamation-sign"></i>验证码不正确');
        if ($this->form_validation->run() == FALSE) {
            $this->load->view('/user/forgetpassword');
        } else {
            $email = $this->input->post("red_email");
 
            if ($this->member->send_mail_resetpassword($email)) {
                $this->load->view("/user/hadSendMail");
            } else {
                show_error("邮件发送失败");
            }
        }
    }
 
    public function forgetemail() {
        $config = array( //字段验证规则
            array(
                "field" => "oldusername",
                "label" => "用户名",
                "rules" => "trim|required|callback_check_username|min_length[4]|max_length[50]"
                ),
            array(
                "field" => "red_password",
                "label" => "密码",
                "rules" => "trim|required|min_length[6]|max_length[20]"
                )
            /*验证码字段
            array(
                "field" => "",
                "label" => "",
                "rules" => ""
                ),*/
            );
        $this->form_validation->set_rules($config);
        $this->form_validation->set_message('required', '<i class="icon-exclamation-sign"></i>此项必填');
        $this->form_validation->set_message('check_username', '<i class="icon-exclamation-sign"></i>用户名格式不正确');
        $this->form_validation->set_message('min_length', '<i class="icon-exclamation-sign"></i>%s长度至少为%s位');
        $this->form_validation->set_message('max_length', '<i class="icon-exclamation-sign"></i>%s长度至多为%s位');
        if ($this->form_validation->run() == FALSE) {
            $this->load->view('/user/forgetemail');
        } else {
            $username = $this->input->post("oldusername");
            $password = $this->input->post("red_password");
 
            $member = $this->member->select_one_by_field("username", $username);
 
            if (empty($member)) {
                $data["error"] = "该用户名不存在";
                $this->load->view("/user/forgetemail", $data);
                return;
            }
 
            if (rd_encode_password($password) != $member["password"]) {
                $data["error"] = "密码错误";
                $this->load->view("/user/forgetemail", $data);
                return;
            }
 
            $data["email"] = $member["email"];
            $this->load->view("/user/getemail", $data);
        }
    }
    //重置密码接口
    public function check_resetpassword() {
        $token = base64_decode($this->input->get("token"));
        $url = $this->input->get("url");
 
        if (empty($token)) {
            log_message("error", "重置密码：没有接受到token信息");
            show_error("密码重置：没有接受到token信息");
        }
        $t = authcode($token, "DECODE", $this->config->item("password_encode_key"));
        $params = explode("_", $t);
        $email = $params[0];
        if (!$this->check_email($email)) {
            show_error("邮箱地址格式不正确");
        }
        $key = $params[1];
        if (!$this->member->check_repassword($email, $key)) {
            show_error("密码重置：重置密码链接出错!");
        } else {
            $_SESSION["resetpassword"] = 1;
            $_SESSION["resetpassword_email"] = $email;
            redirect("/user/resetpassword");
        }
    }
 
    public function resetpassword() {
    	if (!isset($_SESSION["resetpassword"]) || $_SESSION["resetpassword"] != 1) {
    		show_error("请先点击发送邮件后再来");
    	}
        $config = array(
            array(
                "field" => "newpassword",
                "label" => "新密码",
                "rules" => "trim|required|min_length[6]|max_length[20]"
                ),
            array(
                "field" => "repassword",
                "label" => "重复密码",
                "rules" => "trim|required|matches[newpassword]|min_length[6]|max_length[20]"
                )
            );
        $this->form_validation->set_rules($config);
        $this->form_validation->set_message('required', '<i class="icon-exclamation-sign"></i>此项必填');
        $this->form_validation->set_message('min_length', '<i class="icon-exclamation-sign"></i>%s长度至少为%s位');
        $this->form_validation->set_message('max_length', '<i class="icon-exclamation-sign"></i>%s长度至多为%s位');
        $this->form_validation->set_message('matches', '<i class="icon-exclamation-sign"></i>请确保密码一致');
 
        if ($this->form_validation->run() == FALSE) {
            $this->load->view("/user/resetpassword");
        } else {
            $newpassword = trim($this->input->post('newpassword'));
            if ($this->member->changePassword($_SESSION["resetpassword_email"], rd_encode_password($newpassword))) {
                unset($_SESSION["resetpassword"]);
                unset($_SESSION["resetpassword_email"]);
                show_message("修改密码成功，请重新登录", site_url("/user/login"));
            } else {
                unset($_SESSION["resetpassword"]);
                unset($_SESSION["resetpassword_email"]);
                show("修改密码失败");
            }

        }
    }
    
 
    public function bindAppApi() {
        header('Content-type: text/json;charset=utf-8');
 
        $account  = $this->input->post('account');
        $password = $this->input->post('password');
 
        if (empty($account) || $account == "") {
            $account = $this->input->get("account");
        }
 
        if (empty($password)){
            $password = $this->input->get("password");
        }

        if (empty($account)) {
            echo formed_json_data(-1, "account_empty");
            return;
        }
 
        if (empty($password)) { 
            echo formed_json_data(-2, "password_empty");
            return;
        }

        $idnumberPattern = "/^[0-9]{8,9}$/u";
        $emailPattern = "/^[_.0-9a-z-]+@([0-9a-z][0-9a-z-]+.)+[a-z]{2,3}$/u";
 
        $accountValidation = 0;
        if (preg_match($idnumberPattern, $account)) {
            $accountValidation = 1;
            $member = $this->member->select_one_by_field('idnumber', $account);
        }
 
        if (preg_match($emailPattern, $account)) {
            $accountValidation = 1;
            $member = $this->member->select_one_by_field('email', $account);
        }
 
        if ($accountValidation == 0) {
            echo formed_json_data(-3, "account_invalidate");
            return;
        }

        if (empty($member)) {
            echo formed_json_data(-4, "member_notexisted");
            return;
        }

        if ($member["status"] == 0) {
            echo formed_json_data(-5, "member_locked");
            return;
        }

        $ip = get_client_ip();
 
        if ($this->member->check_ip_banned($member["id"], $ip)) {
            echo formed_json_data(-6, "member_failedToMuch");
            return;
        }

        if ($member["password"] != rd_encode_password($password, $member["salt"])){
            $this->member->insert_log($member["id"], $ip, 0);
            $times = $this->member->get_last_login_fails($member["id"], $ip);
            if (intval($times['failedTimes']) >= $this->config->item("maxFailedTimes")) {
                $this->member->insert_ipbanned($member["id"], $ip);
                echo formed_json_data(-6, "member_times_much");
            } else {
                $times = intval($this->config->item("maxFailedTimes")) - intval($times['failedTimes']);
                $data['error'] = '密码错误，还剩余'.$times.'次';
                echo formed_json_data(-7, "password_error");
            }
            return;
        }

        


    }

    public function ajaxLogin() {
        header('Content-type: text/json;charset=utf-8');
 
        $account  = $this->input->post('account');
        $password = $this->input->post('password');
 
        if (empty($account) || $account == "") {
            $account = $this->input->get("account");
        }
 
        if (empty($password)){
            $password = $this->input->get("password");
        }
 
        if (empty($account)) {
            echo formed_json_data(-1, "account_empty");
            return;
        }
 
        if (empty($password)) { 
            echo formed_json_data(-2, "password_empty");
            return;
        }
 
        $idnumberPattern = "/^[0-9]{8,9}$/u";
        $emailPattern = "/^[_.0-9a-z-]+@([0-9a-z][0-9a-z-]+.)+[a-z]{2,3}$/u";
 
        $accountValidation = 0;
        if (preg_match($idnumberPattern, $account)) {
            $accountValidation = 1;
            $member = $this->member->select_one_by_field('idnumber', $account);
        }
 
        if (preg_match($emailPattern, $account)) {
            $accountValidation = 1;
            $member = $this->member->select_one_by_field('email', $account);
        }
 
        if ($accountValidation == 0) {
            echo formed_json_data(-3, "account_invalidate");
            return;
        }
 
        if (empty($member)) {
            echo formed_json_data(-4, "member_notexisted");
            return;
        }
 
        if ($member["status"] == -1) {
            echo formed_json_data(-5, "member_locked");
            return;
        }
 
        $ip = get_client_ip();
 
        if ($this->member->check_ip_banned($member["id"], $ip)) {
            echo formed_json_data(-6, "member_failedToMuch");
            return;
        }
 
        if (!checkHduPassword($member["idnumber"], $password)){
            $this->member->insert_log($member["id"], $ip, 0);
            $times = $this->member->get_last_login_fails($member["id"], $ip);
            if ($times['failedTimes'] >= $this->config->item("maxFailedTimes")) {
                $this->member->insert_ipbanned($member["id"], $ip);
                echo formed_json_data(-5, "member_locked");
            } else {
                $times = intval($this->config->item("maxFailedTimes")) - intval($times['failedTimes']);
                echo formed_json_data(-7, "password_uncorrect");
            }
 
            return;
        }
        //检测教务密码和数据库中保存的密码是否已经发生变化
        if (authcode($member["password"], "DECODE", $this->config->item("password_encode_key")) != $password) {
            if (!$this->member->update_password($member["id"], $password)) {
                log_message("error", "修改已经绑定的密码失败");
                //show_error("修改已经绑定的密码失败，请联系管理员");
            }
        }
 
        $this->passLogin($member, 1);
        $memberData["passid"] = $member["id"];
        $memberData["idnumber"] = $member["idnumber"];
        $memberData["password"] = $password;
        $memberData["emailstatus"] = $member["emailstatus"];
        $memberData["groupid"] = $member["groupid"];
        $memberData["adminid"] = $member["adminid"];
        $memberData["regdate"] = $member["regdate"];
 
        $profile = $this->member->get_profile($member["id"]);
 
        if (empty($profile) || count($profile) == 0) {
            $memberData["realname"]   = null;
            $memberData["gender"]     = null;
            $memberData["birth"]      = null;
            $memberData["mobile"]     = null;
            $memberData["buildingNO"] = null;
            $memberData["roomNO"]     = null;
            $memberData["company"]    = null;
        } else {
            $memberData["realname"]   = $profile["realname"];
            $memberData["gender"]     = $profile["gender"];
            $memberData["birth"]      = $profile["birth"];
            $memberData["mobile"]     = $profile["mobile"];
            $memberData["buildingNO"] = $profile["buildingNO"];
            $memberData["roomNO"]     = $profile["roomNO"];
            $memberData["company"]    = $profile["company"];
        }        
 
        $defaultRole = $this->member->get_default_role($member["id"], 1);
        if (!empty($defaultRole)) {
            $memberData["roleName"]     = $defaultRole["uc_name"];
            $memberData["rolePassword"] = authcode($defaultRole["uc_password"], "DECODE", $this->config->item("password_encode_key"));
            if (empty($memberData["rolePassword"])) {
                $changePasswordStatus = uc_user_edit($memberData["roleName"], null, $memberData["password"], null, 1);
                switch ($changePasswordStatus) {
                case 0:
                    # code...
                    $status = $this->member->changeRolePassword($defaultRole["uc_id"], $password);
                    if (empty($status)) {
                        log_message("error", "ajaxLogin，更改角色密码失败");
                    }
                    $memberData["rolePassword"] = $password;
                    break;
                case 1:
                    $memberData["rolePassword"] = $password;
                    break;
                default:
                    # code...
                    $memberData["rolePassword"] = null;
                    log_message("error", "更新角色密码失败,失败代码为".$changePasswordStatus);
                    break;
                }
                //$memberData["editstatus"] = $changePasswordStatus;
            }
            $memberData["ucid"]         = $defaultRole["uc_id"];
        } else {
            $memberData["roleName"]     = null;
            $memberData["rolePassword"] = null;
            $memberData["ucid"]         = null;
        }
        //$memberData["synLoginCode"] = uc_user_synlogin($memberData["ucid"]);
        /*$synLoginCode = uc_user_synlogin($memberData["ucid"]);
        $loginCodePattern = "/code\=([\w%]*)/u";
        $loginTimePattern = "/time\=([0-9]*)/u";
        preg_match($loginCodePattern, $synLoginCode, $codeMatch);
        preg_match($loginTimePattern, $synLoginCode, $timeMatch);
        $memberData["synLoginCode"] = isset($codeMatch[1]) ? $codeMatch[1]: null;
        $memberData["synLoginTime"] = isset($timeMatch[1]) ? $timeMatch[1]: null;*/
        //$memberData["code"] = $synLoginCode;
 
 
        $libaccount = $this->member->get_lib_password($member["idnumber"]);
        if (empty($libaccount) || count($libaccount) == 0) {
            $memberData["libPassword"] = "null";
        } else {
            $memberData["libPassword"] = authcode($libaccount["password"], "DECODE", $this->config->item("password_encode_key"));
        }
 
        echo formed_json_data(1, "success", $memberData);
        unset($libaccount);
        unset($member);
    }
 
    /*
        绑定图书馆账号api
     */
    public function ajaxChangeHduPassword(){
        header("Content-type:text/json;charset=utf-8");
        $stuID = $this->input->post("stuID");
        $password = $this->input->post("libPw");
 
        if (empty($stuID) || $stuID == "") {
            $stuID = $this->input->get("stuID");
        }
 
        if (empty($password)){
            $password = $this->input->get("libPw");
        }
 
        if (empty($stuID)) {
            echo formed_json_data(-1, "stuID_empty");
            return;
        }
 
        $idnumberPattern = "/^[0-9]{8,9}$/u";
        if (!preg_match($idnumberPattern, $stuID)) {
            echo formed_json_data(-2, "stuID_invalidate");
            return;
        }
 
        $member = $this->member->select_one_by_field('idnumber', $stuID);
 
        if (empty($member)) {
            echo formed_json_data(-3, "account_empty");
            return;
        }
 
        if (!checkLibPassword($stuID, $password)){
            echo formed_json_data(-5, "libPassword_wrong");
            return;
        }
 
        $encodePassword = authcode($password, "encode", $this->config->item("password_encode_key"));
        if (!$this->member->bind_lib_account($stuID, $encodePassword)) {
            echo formed_json_data(-4, "bind_failed");
            return;
        } else {
            echo formed_json_data(1, "bind_succed", array("stuID" => $stuID, "libPassword" => $password));
            return;
        }
    }
 
    //激活邮箱中的接口地址
    public function checkmail() {
        $token = base64_decode($this->input->get("token"));
        $url = $this->input->get("url");
 
        if (empty($token)) {
            log_message("error", "邮箱激活：没有接受到token信息");
            show_error("邮箱激活：没有接受到token信息");
        }
        $t = authcode($token, "DECODE", $this->config->item("password_encode_key"));
        $params = explode("_", $t);
        $passid = $params[0];
        $key = $params[1];
        if (!$this->member->check_email($passid, $key)) {
            log_message("error", "邮箱激活失败");
            $this->load->view("/home/email/checkFailed.php");
            return;
        } else {
            if (empty($url)) {
                redirect("/home/email");
            } else {
                $pattern = "/^".format_preg_string($this->config->item("base_url")).".*$/i";
                if (!preg_match($pattern, $url)) {
                    log_message("error", "网址来源错误");
                    show_message("激活成功", site_url("/home/email"));
                    return;
                }
                redirect($url);
            }
        }
    }
  
    public function checkPasswordInOld($cleartext, $cryptograph) {
        $et = 'md5';
        if (is_array($et))
        {
            return call_user_func($et, $cleartext) == $cryptograph;
        }
        if ($et == 'cleartext') return $cleartext == $cryptograph;
 
        switch ($et)
        {
        case 'md5':
            return md5($cleartext) == $cryptograph;
        case 'crypt':
            return crypt($cleartext, $cryptograph) == $cryptograph;
        case 'sha1':
            return sha1($cleartext) == $cryptograph;
        case 'sha2':
            return hash('sha512', $cleartext) == $cryptograph;
        default:
            return $et($cleartext) == $cryptograph;
        }
    } 
 
    public function check_captcha($captcha) {
    	if (!isset($_SESSION["captcha"])) {
    		return false;
    	}
        //验证码有效期为10分钟
        if ( (time() - $_SESSION["captcha"]['time']) >= 600) {
            unset($_SESSION["captcha"]);
            return false;
        }
 
        if (strtolower($captcha) != strtolower($_SESSION["captcha"]["code"])) {
            unset($_SESSION["captcha"]);
            return false;
        }else {
        	unset($_SESSION["captcha"]);
            return true;
        }
    }

    public function check_username($username) {
        $pattern = "/^[_0-9a-zA-Z]+$/u";
        if (preg_match($pattern, $username)) {
            return TRUE;
        } else {
            return FALSE;
        }
    }

    public function check_email($email) {
        $emailPattern = "/^[_.0-9a-z-]+@([0-9a-z][0-9a-z-]+.)+[a-z]{2,3}$/u";
        if (preg_match($emailPattern, strtolower($email))) {
            return TRUE;
        } else {
            return FALSE;
        }
    }

    public function check_account($account) {
        $emailPattern = "/^[_.0-9a-z-]+@([0-9a-z][0-9a-z-]+.)+[a-z]{2,3}$/u";
        $idnumberPattern = "/^[0-9]{8,9}$/u";
        if (preg_match($emailPattern, $account)) {
            return TRUE;
        } else {
            if (preg_match($idnumberPattern, $account)) {
                return TRUE;
            } else {
                return FALSE;
            }
        }
    }
 
    public function check_stuID($stuID) {
        $pattern = "/^[0-9]{4,9}$/u";
 
        if (preg_match($pattern, $stuID)) {
            return TRUE;
        } else {
            return FALSE;
        }
    }
 
    public function contact() {
        $this->load->view("user/contact");
    }
}